package com.allenkerr.service.impl;

import com.allenkerr.enums.ResultEnum;
import com.allenkerr.mapper.PersonMapper;
import com.allenkerr.model.Person;
import com.allenkerr.service.PersonService;
import com.allenkerr.util.ResultUtils;
import com.allenkerr.vo.Result;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Created by 小柯(Allen Kerr) on 17.6.18 23:54.
 */
@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonMapper personMapper;

    @Override
    public List<Person> findAll(Person person) {
        if (person.getPage() != null && person.getRows() != null)
            PageHelper.startPage(person.getPage(), person.getRows());//设置分页
        return personMapper.selectAll();
    }

    @Override
    public Person findById(Integer id) {
        return personMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Person> findByName(String name) {
        Example example = new Example(Person.class);
        example.createCriteria().andEqualTo("name", name);//设置查询条件
        return personMapper.selectByExample(example);
    }

    @Transactional
    @Override
    public void saveOne(Person person) {
        personMapper.insert(person);
    }

    /**
     * 查找年龄比给定值大的people
     *
     * @param age
     * @return
     */
    @Override
    public List<Person> findAgeGreaterThan(Integer age) {
        Example example = new Example(Person.class);
        example.createCriteria().andGreaterThan("age", age);
        return personMapper.selectByExample(example);
    }

    /**
     * 根据id删除person
     *
     * @param id
     */
    @Override
    public Result deleteById(Integer id) {
        int result = personMapper.deleteByPrimaryKey(id);
        return result > 0 ? ResultUtils.success(ResultEnum.DELETE_SUCCESS) : ResultUtils.fail(ResultEnum.DELETE_FAIL);
    }

    /**
     * 根据name模糊查询people
     *
     * @param name
     * @return
     */
    @Override
    public List<Person> selectByNameLike(String name) {
        return personMapper.selectByNameLike(name);
    }
}
